<template>
<div>
    <div class="info">
        <div class="info hd">基本信息</div>
        <div class="bd">
           <el-form :model="baseForm" :rules="rules" ref="baseForm" label-width="100px" class="baseForm">
            <el-form-item label="景点名称" prop="spotName" class="line-row">
              <el-input v-model="baseForm.spotName" id="input" placeholder="请输入景区名称"></el-input>
            </el-form-item>
            <el-form-item label="景点城市" prop="cityId" class="line-row">
              <el-select v-model="baseForm.cityId" placeholder="请选择活动区域">
                <el-option  v-for="(item,index) in citys" :key="index" :label="item.cityName" :value="item.cityId"></el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="景点地址" prop="address" class="line-row">
              <el-input v-model="baseForm.address"></el-input>
            </el-form-item>
            <el-form-item label="开放时间" required class="line-row">
                <el-col :span="4">
                    <el-form-item prop="openStartTime">
                        <el-time-picker placeholder="开始时间" value-format="HH:mm:ss" v-model="baseForm.openStartTime" style="width: 100%;"></el-time-picker>
                    </el-form-item>
                </el-col>
                <el-col style="text-align: center" :span="1">-</el-col>
                <el-col :span="4">
                    <el-form-item prop="openEndTime">
                        <el-time-picker placeholder="结束时间" value-format="HH:mm:ss" v-model="baseForm.openEndTime" style="width: 100%;"></el-time-picker>
                    </el-form-item>
                </el-col>
            </el-form-item>
            <el-form-item label="景区主题" prop="themes" required>
              <el-col :span="3" v-for="(item,i) in themes" :key="i" style="margin-bottom:10px">
                <el-button @click="selectTheme(item)"  :type="baseForm.themes.indexOf(item.themeId)>-1 ? 'primary': ''">{{item.themeName}}</el-button>
              </el-col>
            </el-form-item>
            <el-row>
              <el-col :span="6">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="baseForm.longitude" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="纬度:" prop="latitude">
                <el-input v-model="baseForm.latitude" disabled></el-input>
               </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-button style="margin-left:30px" @click="getLocation">在地图中搜索景区</el-button>
              </el-col>
            </el-row>
            <el-form-item label-width="46px">
              <div id="container" class="container-map">
               <el-amap vid="amap" :zoom="zoom" :center="center" :plugin="plugin">
                <el-amap-marker v-for="marker in markers" :position="marker.position" :events="events" :key="marker.position.lat"></el-amap-marker>
              </el-amap>
              </div>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="baseForm.status">
                <el-radio  :label="1">上架</el-radio>
                <el-radio  :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>

          </el-form>
        </div>
    </div>
    <div class="info">
      <div class="info hd">附加信息</div>
      <div class="bd">
        <el-form :model="moreForm" ref="moreForm" label-width="100px" class="moreForm">
          <el-form-item label="附加信息" prop="name" required>
              <el-button @click="addInfo">添加</el-button>
          </el-form-item>
        </el-form>
          <!--附加信息-->
          <div class="table-info" v-if="baseForm.addInfoList&&baseForm.addInfoList.length>0">
            <el-table size="mini" border :data="baseForm.addInfoList" style="width: 100%" :header-cell-style="{background: '#DBEDF6'}">
              <el-table-column prop="addInfoName" label="附加信息名称"></el-table-column>
              <el-table-column prop="addDescribe" label="附加信息描述">
                <template slot-scope="scope">
                  <div v-html="scope.row.addDescribe"></div>
                </template>
              </el-table-column>
              <el-table-column prop="" label="操作">
                <template slot-scope="scope">
                   <el-button type="text" size="small" @click="editItem(scope.$index)">编辑</el-button>
                   <el-button type="text" size="small" @click="delItem(scope.$index)">删除</el-button>
                 </template>
              </el-table-column>
            </el-table>
          </div>
      </div>
    </div>
    <div class="info">
      <div class="info hd">景区图片</div>
      <div class="bd">
      <el-form>
          <!--景区封面图-->
          <el-form-item label="封面图" required>
              <el-button size="small" type="primary" @click="openPicDialog(1)">选择封面图</el-button>
          </el-form-item>
          <!--景区封面图-->
          <el-form-item label="封面预览" prop="imageUrl" required v-if="baseForm.imageUrl">
            <div class="preview preview-show" v-if="baseForm.imageUrl!=''">
                    <div class="item">
                        <i class="el-icon-close" @click="baseForm.imageUrl='';uploadDisabled=false"></i>
                        <img :src="baseForm.imageUrl">
                    </div>
              </div>
          </el-form-item>
          <el-form-item label="景区图集" prop="" required>
            <el-col :span="3">
              <el-button size="small" type="primary" @click="openPicDialog(2)">选择图集</el-button>
            </el-col>
          </el-form-item>
          <el-form-item label="" prop="">
            <div class="preview preview-show" v-if="baseForm.images&&baseForm.images.length>0">
                    <div class="item" v-for="(item,index) in baseForm.images" :key="item">
                        <i class="el-icon-close" @click="baseForm.images.splice(index,1);uploadDisabled=false"></i>
                        <img :src="item">
                    </div>
              </div>
          </el-form-item>
      </el-form>
      </div>
    </div>
     <div class="info">
      <div class="info hd">景区介绍</div>
      <div class="bd">
         <tinymce-editor
            v-model="baseForm.introduction"
            ref="editor"
          ></tinymce-editor>
      </div>
    </div>
    <div style="padding: 20px;">
            <el-button @click="submit" type="primary" :disabled="isDisabled">立即提交</el-button>
            <el-button @click="resetForm">重置</el-button>
        </div>
    <!--附加信息dialog-->
    <el-dialog class="add-dialog" :visible.sync="showAddForm" width="600px" title="添加附加信息"  :close-on-press-escape="true">
      <el-form :model="addInfoForm" :rules="addRules" ref="addForm" label-width="120px" class="form-info">
        <el-form-item label="信息名称" prop="addInfoName">
          <el-input v-model="addInfoForm.addInfoName" placeholder="请输入附加信息名称" />
        </el-form-item>
        <el-form-item label="信息描述" prop="addDescribe">
          <el-input type="textarea" :rows="4" placeholder="请输入信息描述" maxlength="500" resize="none" show-word-limit v-model="addInfoForm.addDescribe">
        </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addItem">立即添加</el-button>
          <el-button @click="resetAddForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--封面图 dialog-->
     <el-dialog :title="pictitle" :visible.sync="showPicDialog" width="800px">
        <div class="dialog">
            <div class="tips">*图片大小不得大于100kb</div>
            <div class="upload">
                <div class="action">
                    <div class="btn">
                        <el-upload :action="uploadApi" :disabled="uploadDisabled" :before-upload="beforeAvatarUpload" :headers="uploadHeaders" :on-success="uploadPicSuccess" accept=".jpg,.jpeg,.png" :show-file-list="false">
                            <el-button :disabled="uploadDisabled" size="small" type="plain" icon="el-icon-upload2">点击上传</el-button>
                        </el-upload>
                    </div>
                </div>
                <div class="preview">
                    <div class="item" v-if="pictype==1&&imageUrl">
                        <i class="el-icon-close" @click="imageUrl='';uploadDisabled=false"></i>
                        <img :src="imageUrl">
                    </div>
                </div>
                <div class="preview" v-if="pictype==2&&imgs&&imgs.length>0">
                    <div class="item" v-for="item in imgs" :key="item">
                        <i class="el-icon-close" @click="imgs.splice(index,1);uploadDisabled=false"></i>
                        <img :src="item">
                    </div>
                </div>
                <!--<el-checkbox v-model="picChecked">请确保需要上传的图片已获取版权资质，因上传图片版权问题而使游品库遭受相关损失，应由乙方承担全部责任</el-checkbox>-->
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitPicDialog">上传</el-button>
            <el-button @click="showPicDialog = false">取 消</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
import TinymceEditor from '@/components/editor/editor'
import { setTimeout } from 'timers'
import Cookies from 'js-cookie'
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
const amapManager = new AMapManager()
let Geocoder
export default {
  data () {
    const validateLength = (rule, value, callback) => {
      if (!value || value.length == 0) {
        return callback(new Error('不能为空！'))
      } else {
        callback()
      }
    }
    const self = this
    return {
      spotId: '',
      moreForm: {},
      themes: '',
      baseForm: {
        latitude: '',
        longitude: '',
        themes: [],
        status: 1,
          openStartTime: undefined,
          openEndTime: undefined,
        introduction: '',
        imageUrl: '', // 封面图
        images: [] // 图集 todo
      },
      description: '',
      center: [116.397428, 39.90923], // 中心点坐标
      markers: [],
      map: null,
      zoom: 13,
      geocoder: null,
      events: {
        click: (e) => {
          self.baseForm.longitude = e.lnglat.lng
          self.baseForm.latitude = e.lnglat.lat
          self.center = [e.lnglat.lng, e.lnglat.lat]
          Geocoder.getAddress(self.center, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              console.log('click addr==', result)
              let name = result.regeocode.addressComponent.building
              if (!name) {
                const ares = result.regeocode.addressComponent.businessAreas
                if (ares && ares.length > 0) {
                  name = ares[0].name
                }
              }
              self.baseForm.spotName = name
              self.baseForm.address = result.regeocode.formattedAddress
              self.$nextTick()
            }
          })
        }
      },
      plugin: [
        {
          pName: 'Geocoder',
          events: {
            init (o) {
              Geocoder = o
              o.getAddress(self.center, function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                  console.log(result)
                }
              })
            }
          }
        }],
      rules: {
        spotName: [
          {
            required: true,
            message: '请输入景区名称',
            trigger: 'blur'
          }
        ],
        cityId: [
          {
            required: true,
            message: '请选择景区城市',
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入景区地址',
            trigger: 'blur'
          }
        ],
        latitude: [
          {
            required: true,
            message: '请输入景区纬度',
            trigger: 'blur'
          }
        ],
        longitude: [
          {
            required: true,
            message: '请输入景区经度',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择景区上下架状态',
            trigger: 'blur'
          }
        ],
        imageUrl: [
          {
            required: true,
            message: '请选择封面图',
            trigger: 'blur'
          }
        ],
          openStartTime: [
          {
              required: true,
              message: '请设置开放开始时间',
              trigger: 'blur'
          }
      ],
          openEndTime: [
          {
              required: true,
              message: '请设置开放结束时间',
              trigger: 'blur'
          }
      ],

      },
      citys: '',
      date: '',
      showAddForm: false,
      addInfoForm: {},
      addInfoList: [],
      addRules: {
        addInfoName: [
          {
            required: true,
            message: '请输入附加信息名称',
            trigger: 'blur'
          }
        ],
        addDescribe: [
          {
            required: true,
            message: '请输入附加信息描述',
            trigger: 'blur'
          }
        ]
      },
      activeIdx: '',
      showPicDialog: false,
      uploadApi: `${window.SITE_CONFIG.apiURL}/sys/oss/upload`,
      uploadHeaders: {
        token: Cookies.get('token') || ''
      },
      pictitle: '',
      uploadDisabled: false,
      pictype: '1',
      picChecked: false,
      isDisabled: false,
      imageUrl: '',
      imgs: []
    }
  },
  created () {
    const id = this.$route.params.id || ''
    this.spotId = id
    this.getData()
    this.initMap()
  },
  components: {
    TinymceEditor
  },
  watch: {
    $route: {
      handler (to, form) {
        if (to.name == 'scenicEdit') {
          const id = to.params.id
          this.spotId = id
          this.getInfo()
        }
      },
      deep: true
    }
  },
  computed: {
    showPicFlag () {
      if (this.pictype == '1') {
        return this.baseForm.imageUrl && this.baseForm.imageUrl != ''
      }
      if (this.picctype == '2') {
        return !this.baseForm.images && this.baseForm.images.length != 0
      }
    }
  },
  methods: {

    initMap () {
      const self = this
      this.map = new AMap.Map('container', {
        resizeEnable: true
      })
      this.geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: 'all',
        city: '全国'
      })
      this.$http
        .get('/spot/getSpotInfo', {
          params: {
            spotId: this.spotId
          }
        })
        .then(res => {
          if (res.data.code !== 0) {
            return this.$message.error(res.data.msg)
          }
          const center = [res.data.data.longitude, res.data.data.latitude]
          self.center = center
        })
    },
    getLocation () {
      const address = this.baseForm.spotName
      if (!address) {
        return this.$message.error('请输入景区名称!')
      }
      this.initSearch(this.baseForm.spotName)
      let geocoder = null
      let center = null
      const self = this
      const item = {}
      AMap.service('AMap.Geocoder', function () {
        geocoder = new AMap.Geocoder({
          city: '全国',
          radius: 1000,
          extensions: 'all'
        })
        geocoder.getLocation(address, (status, result) => {
          if (status == 'complete' && result.geocodes.length) {
            const location = result.geocodes[0].location
            center = [location.lng, location.lat]
            self.center = center;
            self.baseForm.latitude = location.lat;
            self.baseForm.longitude = location.lng;
          }
        })
      })
    },
    // 搜索
    initSearch (name) {
      const self = this
      this.map.plugin(
        ['AMap.PlaceSearch', 'AMap.Scale'],
        () => {
          const MSearch = new AMap.PlaceSearch({
            address: name // 城市
          })
          AMap.event.addListener(MSearch, 'complete', (data) => {
            // 添加markers
            const list = data.poiList.pois
            let markers = []
            if (list && list.length > 0) {
              markers = list.map(value => {
                return {
                  position: [
                    value.location.lng,
                    value.location.lat
                  ]
                }
              })
              self.markers = markers
            }
          })
          MSearch.search(name) // 关键字查询
        }
      )
    },
    getInfo () {
      this.$http
        .get('/spot/getSpotInfo', {
          params: {
            spotId: this.spotId
          }
        })
        .then(res => {
          if (res.data.code !== 0) {
            return this.$message.error(res.data.msg)
          }
          const city = res.data.data.cityId || ''
          if (city) {
            res.data.data.cityId = res.data.data.cityId + ''
          }
          this.center = [res.data.data.longitude, res.data.data.latitude]
          this.baseForm = res.data.data
        })
    },
    getData () {
      Promise.all([
        this.$http.get('/form/getScenicThemes'),
        this.$http.get('/form/getScenicCities'),
        this.$http.get('/spot/getSpotInfo', {
          params: {
            spotId: this.spotId
          }
        })
      ]).then(values => {
        console.log(values)
        this.themes = values[0].data.data
        this.citys = values[1].data.data
        const form = values[2].data.data
        const city = form.cityId || ''
        if (city) {
          form.cityId = form.cityId + ''
        }
        const dataThemes = []
        if (form.themes && form.themes.length > 0) {
          form.themes.map(value => {
            dataThemes.push(parseInt(value))
          })
        }
        form.themes = dataThemes
        this.baseForm = form
        this.addInfoList = form.addInfoList
        // 获取日期
        const date = new Date(this.baseForm.openTimeDesc)
      })
    },
    getDate (e) {
      const year = e.getFullYear() + ''
      const month = String(e.getMonth() + 1)
      const day = String(e.getDate())
      const date =
        year +
        '-' +
        month.padStart(2, 0) +
        '-' +
        day.padStart(2, 0) +
        ' 00:00:00'
      this.baseForm.openTimeDesc = date
    },
    // 添加景区信息
    addInfo () {
      this.activeIdx = ''
      for (const key in this.addInfoForm) {
        this.addInfoForm[key] = ''
      }
      this.showAddForm = true
    },
    resetAddForm () {
      this.$nextTick(() => {
        this.$refs.addForm.resetFields()
      })
    },
    // 选择景区主题
    selectTheme (item) {
      if (!this.baseForm.themes) {
        this.baseForm.themes = []
      }
      const index = this.baseForm.themes.indexOf(item.themeId)
      if (index !== -1) {
        this.baseForm.themes.splice(index, 1)
      } else {
        this.baseForm.themes.push(item.themeId)
      }
    },
    // 增加附加信息
    addItem () {
      if (!this.addInfoForm.addInfoName) {
        return this.$message.error('请输入附加信息名称!')
      }
      if (!this.addInfoForm.addDescribe) {
        return this.$message.error('请输入附加信息描述!')
      }

      const item = {
        addDescribe: this.addInfoForm.addDescribe,
        addInfoName: this.addInfoForm.addInfoName
      }
      if (this.activeIdx === '') {
        this.addInfoList.push(item)
      } else {
        this.addInfoList.splice(this.activeIdx, 1, item)
      }
      console.log('addInfoList==', this.addInfoList)
      this.baseForm.addInfoList = this.addInfoList
      this.showAddForm = false

      this.$nextTick(() => {
        this.$refs.addForm.resetFields()
      })
    },
    // 编辑信息
    editItem (idx) {
      this.activeIdx = idx
      const item = this.addInfoList[idx]

      this.addInfoForm = {
        addInfoName: item.addInfoName,
        addDescribe: item.addDescribe
      }
      this.showAddForm = true
    },
    // 删除信息
    delItem (idx) {
      const self = this
      this.$confirm('确认删除该条信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.baseForm.addInfoList.splice(idx, 1)
        self.addInfoList.splice(idx, 1)
        console.log('删除之后的addInfoList==', self.addInfoList)
        self.$message({
          type: 'success',
          message: '删除成功'
        })
      })
    },
    openPicDialog (type) {
      this.showPicDialog = true
      this.pictype = type // 1--- 上传封面图， 2---上传图集
      this.pictitle = type == 1 ? '选择封面图' : '选择图集'
      let flag = false
      if (type == 1) {
        flag = this.baseForm.imageUrl && this.baseForm.imageUrl != ''
      } else {
        flag = false
        // flag= this.baseForm.images && this.baseForm.images.length==5;
      }
      this.uploadDisabled = Boolean(flag)
      console.log('this.baseForm.imageUrl=', this.baseForm.imageUrl)
      console.log('this.baseForm.images=', this.baseForm.images)
    },
    // 上传图片
    submitPicDialog () {
      if (this.pictype == 1) {
        this.baseForm.imageUrl = this.imageUrl
      } else {
        this.baseForm.images = this.baseForm.images.concat(this.imgs)
      }
      this.showPicDialog = false
    },
    beforeAvatarUpload (file) {
      const isLimit = file.size / 1024 < 100
      if (!isLimit) {
        this.$message.error('上传图片大小不能超过100kb!')
      }
      return isLimit
    },
    // 上传图片
    uploadPicSuccess (res, file, filelist) {
      if (this.pictype == 1) {
        this.imageUrl = res.data.src
        this.uploadDisabled = true
      } else {
        this.imgs.push(res.data.src)
        // if (this.imgs.length < 5) {
        //   this.imgs.push(res.data.src);
        //   if (this.imgs.length==5) {
        //     this.uploadDisabled = true;
        //   }
        // } else {
        //   this.uploadDisabled = true;
        // }
      }
    },

    submit () {
      this.baseForm.addInfoList = this.addInfoList
      this.$refs.baseForm.validate(valid => {
        if (!valid) {
          return false
        }
        if (!this.baseForm.themes || this.baseForm.themes.length == 0) {
          return this.$message.error('请选择景区主题!')
        }
        if (!this.baseForm.addInfoList ||this.baseForm.addInfoList.length == 0) {
          return this.$message.error('请添加附加信息!')
        }
        if (!this.baseForm.imageUrl) {
          return this.$message.error('请上传景区封面图!')
        }
        if (!this.baseForm.images || this.baseForm.images.length == 0) {
          return this.$message.error('请上传景区图集!')
        }
        this.$http.post('/spot/update', this.baseForm).then(res => {
          if (res.data.code !== 0) {
            return this.$message.error(res.data.msg)
          }
          this.getInfo()
          this.$message({
            type: 'success',
            message: res.data.msg
          })
        })
      })
    },
    resetForm () {
      for (const key in this.baseForm) {
        if (key != 'themes') {
          this.baseForm[key] = null
        } else {
          this.baseForm[key] = []
        }
      }
      this.baseForm.introduction = ''
      this.themes = []
      // 附加信息
      this.addInfoList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.baseForm {
  .line-row {
    width: 60%;
    min-width: 300px;
  }
}
.container-map {
  width: calc(100% - 0px);
  height: 300px;
  .baidu-map-view {
    height: 300px;
  }
}
.form-info {
  width: calc(100% - 100px);
}
.info {
  margin-top: 10px;

  .hd {
    height: 50px;
    line-height: 50px;
    background: #dbedf6;
    font-weight: bold;
    padding: 0 20px;
    font-size: 16px;
  }

  .bd {
    background: #fff;
    padding: 20px;

    .row {
      display: flex;
      padding: 10px 0;

      .k {
        color: #999;
        width: 150px;
        text-align: right;
        padding-right: 10px;
      }

      .v {
        flex: 1;
        font-weight: 600;

        img {
          width: 145px;
          display: inline-block;
        }
      }
    }

    // .row2 {

    // }
  }
}
.dialog {
  .tips {
    background: #f5f5f5;
    padding: 20px;
  }

  .upload {
    padding: 20px 0;
  }
}
.preview-show {
  margin-left: 52px;
  margin-top: -20px;
}
.preview {
  display: flex;
  flex-flow: row wrap;
  padding-top: 20px;
  video {
    width: 100%;
  }
  .item {
    position: relative;
    margin-right: 10px;
    margin-bottom: 12px;
    width: 180px;

    i.el-icon-close {
      position: absolute;
      width: 14px;
      height: 14px;
      border-radius: 50%;
      background: #666666;
      color: #fff;
      line-height: 14px;
      text-align: center;
      right: -7px;
      top: -7px;
    }

    .v {
      text-align: center;
      cursor: pointer;
      height: 120px;
      line-height: 156px;
      background: #f7f7f7;

      i {
        font-size: 64px;
        color: #666;
      }
    }

    img {
      width: 100%;
    }
  }
}
</style>
